<!doctype html>
<html lang="en">
  <meta charset="utf-8">
  <head>
    <link href='http://twitter.github.com/bootstrap/assets/css/bootstrap.css' rel='stylesheet' />
    <link href='http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css' rel='stylesheet' />
  </head>
  <body>
    <div class="navbar">
      <div class="navbar-inner">
        <div class="container">
          <ul class="nav pull-right">
            <li><span id="user-name"></span><a id="registration" href="#"></a></li>
          </ul>
        </div>
      </div>
    </div>
    <div class="container">
      <h3>Bills with Friends</h3>
      <div id="personal">
        <div class="form-actions">
        <h4>Add a new Bill</h4>
          <form id="add-bill">
            <ul class="inline unstyled">
              <li>
                <div class="input-prepend">
                  <span class="add-on"><i class="icon-info-sign"></i></span>
                  <input required="required" class="span3 purpose" type="text" placeholder="comcast" tabindex="1">
                </div>
              </li>
              <li>
                <div class="input-prepend">
                  <span class="add-on"><i class="icon-envelope"></i></span>
                  <input required="required" class="span3 participants" type="text" placeholder="a@email.com, b@email.com" tabindex="2">
                </div>
              </li>
              <li>
                <div class="input-append input-prepend">
                  <span class="add-on">$</span>
                  <input required="required" class="span1 amount" type="number" placeholder="25" tabindex="3">
                  <span class="add-on">.00</span>
                </div>
              </li>
            </ul>
            <button type="submit" class="btn btn-primary">Submit</button>
            <button type="button" class="btn clear-bill">Clear</button>
          </form>
        </div>
        <h4>Debts</h4>
        <table class="table table-striped table-condensed table-bordered" id="debts">
          <thead>
            <tr>
              <td>Person</td>
              <td>Amount</td>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
        <h4>Bills</h4>
        <table class="table table-striped table-condensed table-bordered" id="bills">
          <thead>
            <tr>
              <td>Purpose</td>
              <td>Participants</td>
              <td>Amount</td>
              <td>Delete</td>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
        <a href="#">previous</a>
        <a href="#">next</a>
      </div>
    </div>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script type="text/javascript">

      $(function() {

        var me;

        var login = $('#registration');
        var username = $('#user-name');
        var form = $('#add-bill');
        var bills = $('#bills');
        var total_bills = 0;

        /**
         * Checked logged in / out state
         */

        $.ajax({
          url: '/api/users/me',
          success: function(resp) {
            // Logged in
            me = resp;
            login.attr('href', '/api/logout').html('logout');
            enableBilling();
          },
          error: function(resp) {
            // Not logged in
            login.attr('href', '/api/login').html('login');
            disableBilling();
          }
        });

        /**
         * Handle
         */

         function enableBilling() {

          // Get and display current bills

          $.ajax({
            url: '/api/Bills?filter=owners==' + me.Id,
            success: function(bills) {
              $.each(bills, function(i, bill) {
                addToBills(bill);
              });
            }
          })

          $('#personal').fadeIn();

          form.find('button[type="submit"]')
            .click(function(e) {
              e.preventDefault();
              // POST to server
              var email = form.find('.email').val();
              var amount = form.find('.amount').val();
              if (!email || !amount) {
                console.log('cannot update because something is missing');
                return;
              }
              $.ajax({
                dataType: 'json',
                contentType: 'application/json',
                type: 'POST',
                url: '/api/Bills/',
                data: JSON.stringify({
                  email: email,
                  amount: amount
                }),
                success: function(bill) {
                  // Update UI
                  form.find('.email').val('');
                  form.find('.amount').val('');
                  addToBills(bill);
                },
                error: function(resp) {
                  console.log('unable to post, please try again');
                }
              });
            });

         }

         function addToBills(bill) {

          var html = '<td>' + bill.purpose + '</td><td>' + bill.participants + '</td><td>' + bill.amount + '</td><td><a href="#" class="delete"><i class="icon-trash"></i></a></td>';

          var tr = $('<tr />').html(html);

          tr.find('.delete').click(function(e) {
            e.preventDefault();
            $.ajax({
              type: 'DELETE',
              url: '/api/Bills/' + bill.Id,
              success: function() {
                tr.fadeOut(function() {
                  tr.remove();
                });
              }
            });
          });

          bills.append(tr);

          total_bills++;

         }

      });

    </script>
  </body>
</html>
